<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title></title>
</head>
<body>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>

<form onsubmit="return false;">
    <h3>WebSocket聊天室：</h3>
    <div>
        <textarea id="responseText" style="width: 500px; height: 300px;"></textarea>
    </div>
    <div>
        <input type="text" name="message" style="width: 430px" value="我是Netty">
        <input id="submit" type="button" value="发送消息">
    </div>

    <div>
        <img id="qrcode_img" src="">
    </div>
</form>

<script th:inline="javascript">
    var socket;

    $(document).ready(function() {
        connet();
    });

    function connet(){
        if (!window.WebSocket) {
            window.WebSocket = window.MozWebSocket;
        }
        if (window.WebSocket) {
            const reqId = [[${reqId}]]

            console.debug("reqId",reqId)

            socket = new WebSocket("ws://localhost:8083/ws?reqId=" + reqId);
            socket.onmessage = function (event) {
                console.log(event);
                const ta = document.getElementById('responseText');
                ta.value = ta.value + '\n' + event.data
            };
            socket.onopen = function (event) {
                var ta = document.getElementById('responseText');
                ta.value = "连接开启!";

                $.ajax({
                    url: "http://localhost:8080/client/login/qrcode?reqId=" + reqId, success: function (result) {
                        $("#qrcode_img").attr("src", result)
                    }
                });
            };
            socket.onclose = function (event) {
                const ta = document.getElementById('responseText');
                ta.value = ta.value + "连接被关闭";
            };
            socket.onerror = function (e) {
                console.debug(e)
            }
        } else {
            alert("你的浏览器不支持 WebSocket！");
        }
    }

    $("#submit").click(function () {
        send($("input[name='message']").val())
    });

    function send(message) {
        if (!window.WebSocket) {
            return;
        }
        if (socket.readyState == WebSocket.OPEN) {
            socket.send(message);
        } else {
            alert("连接没有开启.");
        }
    }
</script>

</body>
</html>